import request from "@/utils/request";
import { Attachment } from "./common/common";

const BASE_URL = "/system/attachment";

const FileAPI = {
  /**
   * 上传文件
   * @param formData
   */
  upload(formData: FormData) {
    return request<any, Attachment>({
      url: `${BASE_URL}/uploadOne`,
      method: "post",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },

  /**
   * 上传文件
   */
  uploadBusinessOne(file: File, businessType?: string, businessId?: string) {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("businessType", businessType || "");
    formData.append("businessId", businessId || "");
    return request<any, Attachment>({
      url: `${BASE_URL}/uploadOne`,
      method: "post",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },

  /**
   * 上传文件
   */
  uploadEditorFile(file: File) {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("businessType", "editor");
    return request<any, Attachment>({
      url: `${BASE_URL}/uploadOne`,
      method: "post",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },

  /**
   * 删除文件
   * @param attachmentId 文件id
   */
  delete(attachmentId?: string) {
    return request({
      url: `${BASE_URL}/delete?attachmentId=${attachmentId}`,
      method: "get",
    });
  },

  /**
   * 下载文件
   * @param url
   * @param fileName
   */
  download(attachmentId?: string, fileName?: string) {
    return request({
      url: `${BASE_URL}/download?attachmentId=${attachmentId}`,
      method: "get",
      responseType: "blob",
    }).then((res) => {
      const blob = new Blob([res.data]);
      const a = document.createElement("a");
      const url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = fileName || "下载文件";
      a.click();
      window.URL.revokeObjectURL(url);
    });
  },
  /**
   * 根据业务类型和id获取附件
   * @param businessId
   * @param businessType
   */
  loadByBusiness(businessId: string, businessType: string) {
    return request<any, Attachment[]>({
      url: `${BASE_URL}/loadByBusiness`,
      method: "get",
      params: { businessId, businessType },
    });
  },
};

export default FileAPI;

// 下载附件地址
export const getFileById = (id?: string) => {
  return id ? `${import.meta.env.VITE_APP_BASE_API}/${BASE_URL}/download?attachmentId=${id}` : "";
};

// 获取附件视频流
export const getVideoUrl = (id?: string) => {
  return id ? `${import.meta.env.VITE_APP_BASE_API}/${BASE_URL}/download?attachmentId=${id}` : "";
};

/**
 * 文件API类型声明
 */
export interface FileInfo {
  /** 文件名 */
  name: string;
  /** 文件路径 */
  url: string;
}

// 文件业务类型
export enum FileBusinessType {
  ACTIVITY_TASK_ITEM = "activity_task_item",
}
